﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MeetingMinutesManager.DB;
using MeetingMinutesManager;
using MeetingMinutesManager.Form;

namespace MeetingMinutesManager
{
    public partial class Default : System.Web.UI.Page
    {
        String user_name = String.Empty;
        String role = String.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            FormUtil.Authenticate(Session, Response);

            if (!IsPostBack)
            {
                user_name = Session["user_name"].ToString().Trim();
                role = Session["role"].ToString().Trim();

                try
                {
                    RefreshTreeView();
                    RefreshGridViews(null);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }
        }

        protected void trvMOMs_SelectedNodeChanged(object sender, EventArgs e)
        {
            try
            {
                RefreshTreeView();
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }
        }

        private void RefreshTreeView()
        {
            int rootIndex = -1;
            int parentIndex = -1;
            int nodeIndex = -1;
            TreeNode selectedNode = trvMOMs.SelectedNode;

            if (selectedNode == null)
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = false;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = false;

                rootIndex = 0;

                RefreshGridViews(null);
            }

            // If select the root
            if (selectedNode == null || selectedNode.Parent == null)
            {
                pnlCategory.Visible = true;
                pnlMoM.Visible = false;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = true;
                btnAddMOM.Visible = false;

                rootIndex = 0;

                RefreshGridViews(null);
            }
            // Select the category node
            else if (selectedNode.Parent != null && selectedNode.Parent.Parent == null)
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = true;
                pnlDetails.Visible = false;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = true;

                rootIndex = trvMOMs.Nodes.IndexOf(selectedNode.Parent);
                parentIndex = selectedNode.Parent.ChildNodes.IndexOf(selectedNode);

                RefreshGridViews(null);
            }
            // Select the mom node
            else
            {
                pnlCategory.Visible = false;
                pnlMoM.Visible = false;
                pnlDetails.Visible = true;

                btnAddCategory.Visible = false;
                btnAddMOM.Visible = false;

                // Refresh Agenda
                String momID = selectedNode.Value;

                RefreshGridViews(momID);

                rootIndex = trvMOMs.Nodes.IndexOf(selectedNode.Parent.Parent);
                parentIndex = selectedNode.Parent.Parent.ChildNodes.IndexOf(selectedNode.Parent);
                nodeIndex = selectedNode.Parent.ChildNodes.IndexOf(selectedNode);

                user_name = Session["user_name"].ToString().Trim();
                role = Session["role"].ToString().Trim();

                MOMOperator.RefreshTreeView(trvMOMs, user_name, role);

                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].ChildNodes[nodeIndex].Select();

                return;
            }

            user_name = Session["user_name"].ToString().Trim();
            role = Session["role"].ToString().Trim();

            MOMOperator.RefreshTreeView(trvMOMs, user_name, role);
            RefreshGridViews(null);

            if (rootIndex != -1 && parentIndex != -1 && nodeIndex != -1)
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].ChildNodes[nodeIndex].Select();
            }
            else if (rootIndex != -1 && parentIndex != -1)
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[rootIndex].ChildNodes[parentIndex].Select();
            }
            else
            {
                trvMOMs.ExpandAll();
                trvMOMs.Nodes[0].Select();
            }
        }

        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            try
            {
                if (MOMOperator.IsCategoryExits(txtCategoryDesc.Text.Trim()))
                {
                    Messenger.Show(Response, "Category already exists!");
                    return;
                }

                String description = txtCategoryDesc.Text.Trim();
                String role = ddlRoles.SelectedValue.Trim();
                String team = ddlTeams.SelectedValue.Trim();

                if (description.Equals(String.Empty) ||
                    role.Equals(String.Empty) ||
                    team.Equals(String.Empty))
                {

                    Messenger.Show(Response, "Need to specify required fields for the category!");
                    return;
                }

                try
                {
                    String strInsertCategory = "insert into mom_type (coldsc, role, team) values ('" + description + "', " + role + ", " + team + ")";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertCategory);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                user_name = Session["user_name"].ToString().Trim();
                role = Session["role"].ToString().Trim();

                MOMOperator.RefreshTreeView(trvMOMs, user_name, role);

                foreach (TreeNode categoryNode in trvMOMs.Nodes[0].ChildNodes)
                {
                    if (categoryNode.Text.Trim().Equals(description.Trim()))
                    {
                        categoryNode.Select();
                        trvMOMs.ExpandAll();

                        RefreshTreeView();
                        RefreshGridViews(null);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            txtCategoryDesc.Text = String.Empty;
            Messenger.Show(Response, "Category Added Successfully!");
        }

        private void RefreshGridViews(String momID)
        {
            if (momID == null)
            {
                RefreshMOM(String.Empty);
                RefreshAgenda(String.Empty);
                RefreshDecision(String.Empty);
                RefreshActions(String.Empty);
                RefreshNotes(String.Empty);
            }
            else
            {
                RefreshMOM(momID);
                RefreshAgenda(momID);
                RefreshDecision(momID);
                RefreshActions(momID);
                RefreshNotes(momID);
            }
        }

        protected void grvMOM_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvMOM.EditIndex = (int)e.NewEditIndex;
            
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvAgenda.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvDecision.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvNotes.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            grvActions.EditIndex = (int)e.NewEditIndex;

            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void grvMOM_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshMOM(momID);
        }

        protected void grvAgenda_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshAgenda(momID);
        }

        protected void grvDecision_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshDecision(momID);
        }

        protected void grvNotes_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshNotes(momID);
        }

        protected void grvActions_OnRowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            String momID = trvMOMs.SelectedNode.Value.Trim();
            RefreshActions(momID);
        }

        protected void btnAddMOM_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode categoryNode = trvMOMs.SelectedNode;
                String category = categoryNode.Value;

                if (MOMOperator.IsMoMExists(category, txtDate.Text.Trim()))
                {
                    Messenger.Show(Response, "MoM with the same title already exists!");
                    return;
                }

                String title = txtDate.Text.Trim();
                String chairman = txtChairman.Text.Trim();
                String duration = txtDuration.Text.Trim();
                String attendee = txtAttendee.Text.Trim();
                String copyto = txtCopyTo.Text.Trim();
                String meeting_date = txtDate.Text.Trim();
                String created_by = txtCreatedBy.Text.Trim();
                String next = txtNextDate.Text.Trim();

                DateTime now = DateTime.Now;
                String created_date = now.ToString("yyyy-MM-dd");

                if (title.Equals(String.Empty) ||
                   chairman.Equals(String.Empty) ||
                   duration.Equals(String.Empty) ||
                   attendee.Equals(String.Empty) ||
                   copyto.Equals(String.Empty) ||
                   meeting_date.Equals(String.Empty) ||
                   created_by.Equals(String.Empty) ||
                   next.Equals(String.Empty))
                {
                    Messenger.Show(Response, "Please fill all required fields!");
                    return;
                }

                try
                {
                    String strInsertMOM = "insert into mom (category, title, chairman, duration, attendee, copyto, meeting_date, created_date, created_by, next) values " +
                        "(" + category + ", '" + title + "', '" + chairman + "', " + duration + ", '" + attendee + "', '" + copyto + "', '" + meeting_date + "', '" + created_date + "', '" + created_by + "', '" + next + "')";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertMOM);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                String newMOMTitle = txtDate.Text.Trim();

                // Clean up the fields
                txtDate.Text = String.Empty;
                txtChairman.Text = String.Empty;
                txtDuration.Text = String.Empty;
                txtAttendee.Text = String.Empty;
                txtCopyTo.Text = String.Empty;
                txtDate.Text = String.Empty;
                txtCreatedBy.Text = String.Empty;
                txtNextDate.Text = String.Empty;

                user_name = Session["user_name"].ToString().Trim();
                role = Session["role"].ToString().Trim();

                MOMOperator.RefreshTreeView(trvMOMs, user_name, role);

                foreach (TreeNode categoryNodeToVerify in trvMOMs.Nodes[0].ChildNodes)
                {
                    if (categoryNodeToVerify.Value.Trim().Equals(category.Trim()))
                    {
                        foreach (TreeNode momNodeToVerify in categoryNodeToVerify.ChildNodes)
                        {
                            if (momNodeToVerify.Text.Trim().Equals(newMOMTitle))
                            {
                                momNodeToVerify.Select();
                                trvMOMs.ExpandAll();

                                String momID = momNodeToVerify.Value.Trim();

                                RefreshTreeView();
                                RefreshGridViews(momID);

                                break;
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "MoM Added Successfully!");
        }

        protected void btnAddAgenda_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode momNode = trvMOMs.SelectedNode;
                String momID = momNode.Value;

                String agenda = txtAgenda.Text.Trim();
                agenda = agenda.Replace("\'", "\"");
                String duration = txtAgendaDuration.Text.Trim();
                String presenter = txtPresenter.Text.Trim();

                if (agenda.Equals(String.Empty) ||
                   presenter.Equals(String.Empty) ||
                   duration.Equals(String.Empty))
                {
                    Messenger.Show(Response, "Please fill all required fields!");
                    return;
                }

                try
                {
                    String strInsertAgenda = "insert into mom_agenda (mom_id, agenda, duration, presenter) values " +
                        "(" + momID + ", '" + agenda + "', " + duration + ", '" + presenter + "')";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertAgenda);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                // Clean up the fields
                txtAgenda.Text = String.Empty;
                txtAgendaDuration.Text = String.Empty;
                txtPresenter.Text = String.Empty;

                RefreshGridViews(momID);

            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Agenda Added Successfully!");
        }

        protected void btnAddDecision_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode momNode = trvMOMs.SelectedNode;
                String momID = momNode.Value;

                String decision = txtDecision.Text.Trim();
                decision = decision.Replace("\'", "\"");
                String decisionMaker = txtMaker.Text.Trim();

                if (decision.Equals(String.Empty) ||
                   decisionMaker.Equals(String.Empty))
                {
                    Messenger.Show(Response, "Please fill all required fields!");
                    return;
                }

                try
                {
                    String strInsertDecision = "insert into mom_decision (mom_id, decision, maker) values " +
                        "(" + momID + ", '" + decision + "', '" + decisionMaker + "')";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertDecision);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                // Clean up the fields
                txtDecision.Text = String.Empty;
                txtMaker.Text = String.Empty;

                RefreshGridViews(momID);

            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Decision Added Successfully!");
        }

        protected void btnAddNote_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode momNode = trvMOMs.SelectedNode;
                String momID = momNode.Value;

                String note = txtNote.Text.Trim();
                note = note.Replace("\'", "\"");

                if (note.Equals(String.Empty))
                {
                    Messenger.Show(Response, "Please fill all required fields!");
                    return;
                }

                try
                {
                    String strInsertNote = "insert into mom_notes (mom_id, notes) values " +
                        "(" + momID + ", '" + note + "')";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertNote);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                // Clean up the fields
                txtNote.Text = String.Empty;

                RefreshGridViews(momID);

            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Notes Added Successfully!");
        }

        protected void btnAddAction_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode momNode = trvMOMs.SelectedNode;
                String momID = momNode.Value;

                String action = txtAction.Text.Trim();
                action = action.Replace("\'", "\"");
                String status = "Open";
                String dueDate = txtActionDueDate.Text.Trim();
                String owner = ddlOwners.SelectedValue.Trim();

                if (action.Equals(String.Empty) ||
                   status.Equals(String.Empty) ||
                   dueDate.Equals(String.Empty) ||
                   owner.Equals(String.Empty))
                {
                    Messenger.Show(Response, "Please fill all required fields!");
                    return;
                }

                try
                {
                    String strInsertDecision = "insert into mom_action (mom_id, action, status, duedate, owner) values " +
                        "(" + momID + ", '" + action + "', '" + status + "', '" + dueDate + "', '" + owner + "')";
                    DBOperator localOperator = new DBOperator(DBConfigurations.LOCAL_CONNECTION_STRING);
                    localOperator.Update(strInsertDecision);
                }
                catch (Exception ex)
                {
                    Messenger.Show(Response, "Error: " + ex.Message);
                    return;
                }

                // Clean up the fields
                txtAction.Text = String.Empty;
                txtActionDueDate.Text = String.Empty;
                ddlOwners.SelectedIndex = -1;

                RefreshGridViews(momID);

            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                return;
            }

            Messenger.Show(Response, "Action Added Successfully!");
        }

        private void RefreshMOM(String momID)
        {
            // Clear the DataSourceID
            if (momID.Equals(String.Empty))
            {
                SqlDataSource1.SelectCommand = "select * from mom where 1 = 2";
            }
            else
            {
                SqlDataSource1.SelectCommand = "select * from mom where id = " + momID + " order by id";
            }

            SqlDataSource1.DataBind();

            //// Set DataSource
            //DataTable dt = MOMOperator.ReadMOMForGridView(momID);

            //grvMOM.DataSource = dt.DefaultView;
            //grvMOM.DataBind();

            //// Set DataSourceID
            //grvMOM.DataSource = null;
            //grvMOM.DataSourceID = "SqlDataSource1";
        }

        private void RefreshAgenda(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceAgenda.SelectCommand = "select * from mom_agenda where 1 = 2";
            }
            else
            {
                SqlDataSourceAgenda.SelectCommand = "select * from mom_agenda where mom_id = " + momID + " order by id";
            }
            SqlDataSourceAgenda.DataBind();
        }

        private void RefreshDecision(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceDecision.SelectCommand = "select * from mom_decision where 1 = 2";
            }
            else
            {
                SqlDataSourceDecision.SelectCommand = "select * from mom_decision where mom_id = " + momID + " order by id";
            }

            SqlDataSourceDecision.DataBind();
        }

        private void RefreshActions(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceActions.SelectCommand = "select * from mom_action where 1 = 2";
            }
            else
            {
                SqlDataSourceActions.SelectCommand = "select * from mom_action where mom_id = " + momID + " order by [owner], action";
            }

            SqlDataSourceActions.DataBind();
        }

        private void RefreshNotes(String momID)
        {
            if (momID.Equals(String.Empty))
            {
                SqlDataSourceNotes.SelectCommand = "select * from mom_notes where 1 = 2";
            }
            else
            {
                SqlDataSourceNotes.SelectCommand = "select * from mom_notes where mom_id = " + momID + " order by id";
            }

            SqlDataSourceNotes.DataBind();
        }

        protected void btnActionReminder_Click(object sender, EventArgs e)
        {
            // If the selected node is not a MOM ID, then return
            TreeNode selectedNode = trvMOMs.SelectedNode;

            if (selectedNode == null // No node selected
                || selectedNode.Parent == null // root node selected
                || selectedNode.Parent.Parent == null // MOM type node selected
                )
            {
                Messenger.Show(Response, "Please Select a MOM then proceed.");
                return;
            }

            // If select the mom node
            String momID = selectedNode.Value;
            DataTable dt = MOMOperator.ReadActions(momID);

            MOMOperator.SendActionReminder(momID);

            Messenger.Show(Response, "Reminder Sent");
        }

        protected void btnMaintenance_Click(object sender, EventArgs e)
        {
            if (!FormUtil.AuthenticateManager1(Session, Response))
            {
                Messenger.Show(Response, "Access Denied!");
                return;
            }

            PopupForm popup = new PopupForm(Response, "Maintenance/Dashboard.aspx", "MaintenanceDashboard", "275", "200", "250", "200");
            popup.Popup();
        }
    }
}
